<?php
include "include/config.inc.php";

if(!isset($_SESSION['s_activId']))
{
  header('location:index.php');
}
$today       = date("d-m-Y");
$msg         = "";
$m           = 0;
$lastId      = "";
$accountName = "";

//Edit loanId
$editLoanRow = "";
//echo "<pre>";
//print_r($_POST);
//echo "</pre>";
if(isset($_POST['loanDetailId']))
{
  $loanDetailId = $_POST['loanDetailId'];
  $editLoan     = "SELECT grossWeight, less, purity, fine, rate, goldValue, landValue, propartyValue, 
                          constructionValue, value, itemImage, monthlyInterest, monthlyInterestRs
                     FROM loan
                    WHERE loanId = ".$loanDetailId;
  $editLoanRes  = mysql_query($editLoan) or die("Error...".mysql_error());
  $editLoanRow  = mysql_fetch_array($editLoanRes);
}

if(isset($_POST['loanBtn']) || isset($_POST['loanPrintBtn']))
{                                                 
  $accountName  = isset($_POST['accountName']) ? $_POST['accountName'] : "";
  $partyCode    = isset($_POST['partyCode']) ? $_POST['partyCode'] : "";
  $address      = isset($_POST['address']) ? $_POST['address'] : "";
  $mobile       = isset($_POST['mobile']) ? $_POST['mobile'] : "";
  $otherInfo    = isset($_POST['otherInfo']) ? $_POST['otherInfo']:"";
  $value        = isset($_POST['value']) && $_POST['value'] != '' ? $_POST['value'] : 0;
  $photo        = isset($_FILES['photo']['name']) ? $_FILES['photo']['name'] : "";
  
  if($_POST['accountIdOld'] == 0)
  { 
    $insPartyTb    = "INSERT INTO `account` (`accountName`, `partyCode`, `address`, `mobile`, `photo`, `otherInfo`,`isParty`)
                      VALUES ('".$accountName."', '".$partyCode."', '".$address."', '".$mobile."', '".$_FILES['photo']['name']."',
                              '".$otherInfo."',1)";
    $insPartyTbRes = mysql_query($insPartyTb);
    if(!$insPartyTbRes)
    {
      echo "Insert Error : ".mysql_error();
    }
    $accountId       = mysql_insert_id();
    
    if(isset($_FILES['photo']['name']) && $_FILES['photo']['name'] != "")
    {
      $filename  = pathinfo($_FILES['photo']['name']);
      $extension = $filename['extension'];
      $stamp     = strtotime($today);
      $image     = "partyImg_".$accountId."_".$stamp.".".$extension;
      $file      = "partyUplodeadImages/".$image;
      move_uploaded_file($_FILES['photo']['tmp_name'], $file); 
     
      $updateImage    = "UPDATE account
                            SET photo = '".$image."'
                          WHERE accountId = ".$accountId;
      $updateImageRes = mysql_query($updateImage);
      if(!$updateImageRes)
      {
        echo "Update Image Error : ".mysql_error();
      }      
    }
  }
  else
  {
  	$img = $_FILES['photo']['name'];
    if($img != "")
    {
      $updateParty = "UPDATE account 
                         SET accountName = '".$accountName."',
                             address     = '".$address."',
                             mobile      = '".$mobile."',
                             otherInfo   = '".$otherInfo."'
                       WHERE accountId   = ".$_POST['accountIdOld'];
      $updatePartyRes = mysql_query($updateParty);
      if(!$updatePartyRes)
      {
        echo "Update Party Error : ".mysql_error();
      }      
      $accountId        = $_POST['accountIdOld'];
      if(isset($_FILES['photo']['name']))
      {
        $filename  =  pathinfo($_FILES['photo']['name']);
        $extension = $filename['extension'];
        $image     = "partyImg_".$accountId.".".$extension;
        $file      = "partyUplodeadImages/".$image;
        move_uploaded_file($_FILES['photo']['tmp_name'], $file); 
       
        $updateImage = "UPDATE account
                           SET photo = '".$image."'
                         WHERE accountId = ".$accountId;
        $updateImageRes = mysql_query($updateImage);
        if(!$updateImageRes)
        {
          echo "Update Image Error : ".mysql_error();
        }         
      }
    }
    else
    {
      $updateParty    = "UPDATE account 
                            SET accountName = '".$accountName."',
                                address     = '".$address."',
                                mobile      = '".$mobile."',
                                otherInfo   = '".$otherInfo."'
                          WHERE accountId   = ".$_POST['accountIdOld'];
      $updatePartyRes = mysql_query($updateParty);
      if(!$updatePartyRes)
      {
        echo "Update Party Error : ".mysql_error();
      }      
    }
    if(!empty($_POST['accountIdOld']))
    {
      $accountId	= $_POST['accountIdOld'];	     	
    }
  }
  $loanVar = substr($accountName, 0, 1);
  
  ////set No Selection : Start
  $loanVarNo = "";
  $selectloanVarNo       = "SELECT loanVar
                              FROM loan
                             WHERE loanVar = '".$loanVar."'";
  $selectloanVarNoResult = mysql_query($selectloanVarNo);
  $countRow              = mysql_num_rows($selectloanVarNoResult);
  
  $countCharNo       = $countRow + 1;
  
  $loanVarNo         = $loanVar."".$countCharNo;
  
  $loanDate          = $_REQUEST['curDateYear']."-".$_REQUEST['curDateMonth']."-".$_REQUEST['curDateDay'];
  $lastInterastDate  = $_REQUEST['lastInstRecYear']."-".$_REQUEST['lastInstRecMonth']."-".$_REQUEST['lastInstRecDay'];
  $endDate           = $_REQUEST['endDateYear']."-".$_REQUEST['endDateMonth']."-".$_REQUEST['endDateDay'];
  $loanType          = isset($_POST['loanType']) && $_POST['loanType'] != '' ? $_POST['loanType'] : '';
  $loadAmount        = isset($_POST['loadAmount']) && $_POST['loadAmount'] != '' ? $_POST['loadAmount'] : 0;
  $itemLocation      = isset($_POST['itemLocation']) && $_POST['itemLocation'] != '' ? $_POST['itemLocation'] : '';
  $monthlyInterest   = isset($_POST['monthlyInterest']) && $_POST['monthlyInterest'] != '' ? $_POST['monthlyInterest'] : 0;
  $monthlyInterestRs = isset($_POST['monthlyInterestRs']) && $_POST['monthlyInterestRs'] != '' ? $_POST['monthlyInterestRs'] : 0;
  
  $grossWeight       = isset($_POST['grossWeight']) && $_POST['grossWeight'] != '' ? $_POST['grossWeight'] : 0;
  $less              = isset($_POST['less']) && $_POST['less'] != '' ? $_POST['less'] : 0;
  $purity            = isset($_POST['purity']) && $_POST['purity'] != '' ? $_POST['purity'] : 0;
  $fine              = isset($_POST['fine']) && $_POST['fine'] != '' ? $_POST['fine'] : 0;
  $rate              = isset($_POST['Rate']) && $_POST['Rate'] != '' ? $_POST['Rate'] : 0;
  $image             = isset($_POST['image']) && $_POST['image'] !=''  ? $_POST['image'] : "";
  $goldValue         = isset($_POST['goldValue']) && $_POST['goldValue'] !='' ? $_POST['goldValue'] : 0;
  $landValue         = isset($_POST['landValue']) && $_POST['landValue'] !='' ? $_POST['landValue'] : 0;
  $constructionValue = isset($_POST['constructionValue']) && $_POST['constructionValue'] !='' ? $_POST['constructionValue'] : 0;
  $propartyValue     = isset($_POST['propartyValue']) && $_POST['propartyValue'] !='' ? $_POST['propartyValue'] : 0;
  
  
  
  if(isset($_FILES['file']['name']) && $_FILES['file']['name'] != "")
  {
  	$today     = date('Y-m-d h:i:s');
    $filename  =  pathinfo($_FILES['file']['name']);
    $extension = $filename['extension'];
    $image     = "loanImg_".strtotime($today).".".$extension;
    $file      = "loanUplodeadImages/".$image;
    move_uploaded_file($_FILES['file']['tmp_name'], $file); 
  }
  $ckeckItemlocationAvailablity       = "SELECT itemlocationId
                                           FROM itemlocation 
                                          WHERE itemlocationName ='".$itemLocation."' ";
  $ckeckItemlocationAvailablityRes    = mysql_query($ckeckItemlocationAvailablity);
  $ckeckItemlocationAvailablityRow    = mysql_fetch_array($ckeckItemlocationAvailablityRes);
  $ckeckItemlocationAvailablityNumRow = mysql_num_rows($ckeckItemlocationAvailablityRes);
  if($ckeckItemlocationAvailablityNumRow > 0)
  {
    $itemlocationId = $ckeckItemlocationAvailablityRow['itemlocationId'];
  }
  else
  {
    $insItemlocation    = "INSERT INTO `itemlocation` (`itemlocationName`)
                           VALUES ('".$itemLocation."')";
    $insItemlocationRes = mysql_query($insItemlocation);
    $itemlocationId     = mysql_insert_id();
  }
    
  $insLoan  = "INSERT INTO  `loan` (`accountId`,`loanType`,`loanAmount`,currentLoanAmount,`pendingAmount`, `value`,`itemlocationId`, `itemImage`,`loanDate`, 
                                    `lastInterestReceiveDate` ,`endDate`,`monthlyInterest`, `monthlyInterestRs`,`loanVar`,
                                    `loanVarNo`,`grossWeight`,`less`,`purity`,`fine`,`rate`,`goldValue`, `landValue`,
                                    `constructionValue`,`propartyValue`)
                    VALUES ('".$accountId."','".$loanType."','".$loadAmount."','".$loadAmount."','".$loadAmount."', '".$value."', '".$itemlocationId."',
                            '".$image."', '".$loanDate."', '".$lastInterastDate."', '".$endDate."', '".$monthlyInterest."', 
                            '".$monthlyInterestRs."', '".$loanVar."', '".$loanVarNo."', '".$grossWeight."', '".$less."',
                            '".$purity."', '".$fine."', '".$rate."', '".$goldValue."', ".$landValue.", ".$constructionValue.",
                            ".$propartyValue.")";
  $insLoanRes = mysql_query($insLoan);
  if(!$insLoanRes)
  {
    echo "Insert loan Error 1: ".mysql_error();
  }    
  $lastId     = mysql_insert_id();

  //Update Gold Rate
  $gold    = "UPDATE goldrate
                 SET goldRate = ".$goldValue;
  $goldRes = mysql_query($gold);

  if($loanType == 'Diary')
  {
  	//Insert Transaction : Start
	  
		//Voucher No Selection : Start
		$selectVoucherNo = "SELECT transDate
		                      FROM transmaster
		                     WHERE transDate = '".$loanDate."'";
		$selectVoucherNoResult = mysql_query($selectVoucherNo);
		$countRow = mysql_num_rows($selectVoucherNoResult);
		$transDateNew = date("d-m-Y", strtotime($loanDate));
		if($countRow > 0)
		{
		  $voucherNoCount = $countRow + 1;
		  if($voucherNoCount < 10)
		  {
		    $voucherNoSet = $transDateNew.'-0'.$voucherNoCount;
		  }
		  else
		  {
		  	$voucherNoSet = $transDateNew.'-'.$voucherNoCount;
		  }
		}
		else
		{
		  $voucherNoSet = $transDateNew.'-01';
		}
		////Voucher No Selection : End    
	  
	  $insTransMasterQry = "INSERT INTO transmaster (voucherType,transDate,voucherNo,loanId)
	                        VALUES ('Loan','".$loanDate."','".$voucherNoSet."',".$lastId.")";
	  $insTransMasterQryRes = mysql_query($insTransMasterQry);
	  $lastTransMasterId = mysql_insert_id();
	  if(!$insTransMasterQryRes)
	  {
	  	echo "Insert Trans Master Not Inserted".mysql_error();
	  }
	
	  $loopCount = 0;
	  $totDrAmount = 0;
	  while($loopCount < count($_POST['accountId']))
	  {
	    $crAccountId     = isset($_POST['accountId'][$loopCount]) ? $_POST['accountId'][$loopCount] : 0;
	    $amountNarration = isset($_POST['amountNarration'][$loopCount]) ? $_POST['amountNarration'][$loopCount] : 0;
	    $amount1         = isset($_POST['amount1'][$loopCount]) ? $_POST['amount1'][$loopCount] : 0;
	    $crAmount        = isset($_POST['amount2'][$loopCount]) ? $_POST['amount2'][$loopCount] : 0;   	
	    $totDrAmount    += $crAmount;
	    if($crAccountId > 0)
	    {
	      $insertCrDetail  = "INSERT INTO transdetail (transMasterId,crAccountId,crAmount,amount1,amountNarration)
	                          VALUES (".$lastTransMasterId.",".$crAccountId.",".$crAmount.",".$amount1.",'".$amountNarration."')";
	      $insertCrDetailRes = mysql_query($insertCrDetail);
	      if(!$insertCrDetailRes)
	      {
	        echo "Insert Transaction 11 Detail Error : ".mysql_error();
	      }
	    }
	    $loopCount++;
	  }
	  $drAccountId  = $accountId;
	  $drAmount13st = (($totDrAmount + $monthlyInterestRs)*7)/100;
	  $drAmountLast = (($totDrAmount + $monthlyInterestRs)*9)/100;
	  
	  $loopCount = 0;
    while($loopCount < 13)
    {
      $insertDrDetail  = "INSERT INTO transdetail (transMasterId,drAccountId,drAmount)
		                      VALUES (".$lastTransMasterId.",".$drAccountId.",".$drAmount13st.")";
		  $insertDrDetailRes = mysql_query($insertDrDetail);
		  if(!$insertDrDetailRes)
		  {
		    echo "Insert Transaction 22 Detail 13st Error : ".mysql_error();
		  }
      $loopCount++;
    }
    
	  $insertDrDetail  = "INSERT INTO transdetail (transMasterId,drAccountId,drAmount)
	                      VALUES (".$lastTransMasterId.",".$drAccountId.",".$drAmountLast.")";
	  $insertDrDetailRes = mysql_query($insertDrDetail);
	  if(!$insertDrDetailRes)
	  {
	    echo "Insert Transaction 22 Detail Last Error : ".mysql_error();
	  }
	  
	  $selAccAvailQry = "SELECT accountId
	                       FROM account
	                      WHERE accountName = 'Interest Income'";
	  $selAccAvailQryRes = mysql_query($selAccAvailQry);
	  if($accRow = mysql_fetch_array($selAccAvailQryRes))
	  {
		  $interestAccountId = $accRow['accountId'];
	  }
	  else
	  {
		  $interestAccountId = 0;
	  }
	  
	  $insertCrDetail  = "INSERT INTO transdetail (transMasterId,crAccountId,crAmount)
	                      VALUES (".$lastTransMasterId.",".$interestAccountId.",".$monthlyInterestRs.")";
	  $insertCrDetailRes = mysql_query($insertCrDetail);
	  if(!$insertCrDetailRes)
	  {
	    echo "Monthly Interest Cr Detail 2 Error : ".mysql_error();
	  }    
	  //Insert Transaction : End
	
	  if($loanDate < $lastInterastDate)
	  {
	    for($l=$loanDate;$l<=$lastInterastDate;$l=date ("Y-m-d", strtotime("+30 day", strtotime($l))))
	    {
	      $insertInterestRecived    = "INSERT INTO `interestreceived` (`loanId`, `pendingAmount`, `interest`, `dateOfInstallment`, `receivedDate`, `isReceive`)
	                                   VALUES ('".$lastId."','".$loadAmount."','".$monthlyInterestRs."','".$l."','".$l."',1)";
	      $insertInterestRecivedRes = mysql_query($insertInterestRecived);
	      if(!$insertInterestRecivedRes)
	      {
	        echo "Insert interestreceived Error : ".mysql_error();
	      }         
	    } 
	  }
	  
	  if(isset($_POST['loanPrintBtn']))
	  {
	    header("location:billListSimple.php?loanId=".$lastId);
	  }
  }
  else
  {
	  //Insert Transaction : Start
	  
		//Voucher No Selection : Start
		$selectVoucherNo = "SELECT transDate
		                      FROM transmaster
		                     WHERE transDate = '".$loanDate."'";
		$selectVoucherNoResult = mysql_query($selectVoucherNo);
		$countRow = mysql_num_rows($selectVoucherNoResult);
		$transDateNew = date("d-m-Y", strtotime($loanDate));
		if($countRow > 0)
		{
		  $voucherNoCount = $countRow + 1;
		  if($voucherNoCount < 10)
		  {
		    $voucherNoSet = $transDateNew.'-0'.$voucherNoCount;
		  }
		  else
		  {
		  	$voucherNoSet = $transDateNew.'-'.$voucherNoCount;
		  }
		}
		else
		{
		  $voucherNoSet = $transDateNew.'-01';
		}
		////Voucher No Selection : End    
	  
	  $insTransMasterQry = "INSERT INTO transmaster (voucherType,transDate,voucherNo,loanId)
	                        VALUES ('Loan','".$loanDate."','".$voucherNoSet."',".$lastId.")";
	  $insTransMasterQryRes = mysql_query($insTransMasterQry);
	  $lastTransMasterId = mysql_insert_id();
	  if(!$insTransMasterQryRes)
	  {
	  	echo "Insert Trans Master Not Inserted".mysql_error();
	  }
	
	  $loopCount = 0;
	  $totDrAmount = 0;
	  while($loopCount < count($_POST['accountId']))
	  {
	    $crAccountId     = isset($_POST['accountId'][$loopCount]) ? $_POST['accountId'][$loopCount] : 0;
	    $amountNarration = isset($_POST['amountNarration'][$loopCount]) ? $_POST['amountNarration'][$loopCount] : 0;
	    $amount1         = isset($_POST['amount1'][$loopCount]) ? $_POST['amount1'][$loopCount] : 0;
	    $crAmount        = isset($_POST['amount2'][$loopCount]) ? $_POST['amount2'][$loopCount] : 0;   	
	    $totDrAmount    += $crAmount;
	    if($crAccountId > 0)
	    {
	      $insertCrDetail  = "INSERT INTO transdetail (transMasterId,crAccountId,crAmount,amount1,amountNarration)
	                          VALUES (".$lastTransMasterId.",".$crAccountId.",".$crAmount.",".$amount1.",'".$amountNarration."')";
	      $insertCrDetailRes = mysql_query($insertCrDetail);
	      if(!$insertCrDetailRes)
	      {
	        echo "Insert Transaction 11 Detail Error : ".mysql_error();
	      }
	    }
	    $loopCount++;
	  }
	  $drAccountId     = $accountId;
	  $drAmount        = $totDrAmount;   	
	  $insertDrDetail  = "INSERT INTO transdetail (transMasterId,drAccountId,drAmount)
	                      VALUES (".$lastTransMasterId.",".$drAccountId.",".$drAmount.")";
	  $insertDrDetailRes = mysql_query($insertDrDetail);
	  if(!$insertDrDetailRes)
	  {
	    echo "Insert Transaction 22 Detail Error : ".mysql_error();
	  }     
	  
	  $selAccAvailQry = "SELECT accountId
	                       FROM account
	                      WHERE accountName = 'Interest Income'";
	  $selAccAvailQryRes = mysql_query($selAccAvailQry);
	  if($accRow = mysql_fetch_array($selAccAvailQryRes))
	  {
		  $interestAccountId = $accRow['accountId'];
	  }
	  else
	  {
		  $interestAccountId = 0;
	  }
	  
	  $insertDrDetail  = "INSERT INTO transdetail (transMasterId,drAccountId,drAmount)
	                      VALUES (".$lastTransMasterId.",".$drAccountId.",".$monthlyInterestRs.")";
	  $insertDrDetailRes = mysql_query($insertDrDetail);
	  if(!$insertDrDetailRes)
	  {
	    echo "Monthly Interest Dr Detail 2 Error : ".mysql_error();
	  }    
	
	  $insertCrDetail  = "INSERT INTO transdetail (transMasterId,crAccountId,crAmount)
	                      VALUES (".$lastTransMasterId.",".$interestAccountId.",".$monthlyInterestRs.")";
	  $insertCrDetailRes = mysql_query($insertCrDetail);
	  if(!$insertCrDetailRes)
	  {
	    echo "Monthly Interest Cr Detail 2 Error : ".mysql_error();
	  }    
	  //Insert Transaction : End
	
	   
	   
	  if($loanDate < $lastInterastDate)
	  {
	    for($l=$loanDate;$l<=$lastInterastDate;$l=date ("Y-m-d", strtotime("+30 day", strtotime($l))))
	    {
	      $insertInterestRecived    = "INSERT INTO `interestreceived` (`loanId`, `pendingAmount`, `interest`, `dateOfInstallment`, `receivedDate`, `isReceive`)
	                                   VALUES ('".$lastId."','".$loadAmount."','".$monthlyInterestRs."','".$l."','".$l."',1)";
	      $insertInterestRecivedRes = mysql_query($insertInterestRecived);
	      if(!$insertInterestRecivedRes)
	      {
	        echo "Insert interestreceived Error : ".mysql_error();
	      }         
	    } 
	  }
	  
	  if(isset($_POST['loanPrintBtn']))
	  {
	    header("location:billListSimple.php?loanId=".$lastId);
	  }
	}
  
//  echo $hiddenId = $_POST['hiddenId'];
//  if($hiddenId == 1)
//  {
//    header("location:loanEdit.php?loanDetailId=".$lastId);
//  }
}
$m = 0;
$selAccountArray = array();
$selAccountQry = "SELECT accountId,accountName
                    FROM account
                   WHERE isDayBook = 1";
$selAccountQryRes = mysql_query($selAccountQry);
while($accRow = mysql_fetch_array($selAccountQryRes))
{
  $selAccountArray['accountId'][$m] = $accRow['accountId'];
  $selAccountArray['accountName'][$m] = $accRow['accountName'];
  $m++;
}
$i=0;
$arrParty    = array();
$selParty    = "SELECT `accountId`,`accountName` 
                  FROM `account`
                  WHERE isParty = 1";
$selPartyRes = mysql_query($selParty);
while($selPartyResRow=mysql_fetch_array($selPartyRes))
{
  $arrParty['accountName'][$i] = $selPartyResRow['accountName'];
  $arrParty['accountId'][$i]   = $selPartyResRow['accountId'];
  $i++;
}

$loanTypeArr[0] = 'Monthly';
$loanTypeArr[1] = 'Daily';
$loanTypeArr[2] = 'Diary';
include("bottom.php");
//////fetch the party Name Over
$smarty->assign('arrParty',$arrParty); 
$smarty->assign('lastId',$lastId);   
$smarty->assign('selAccountArray',$selAccountArray);  
$smarty->assign('editLoanRow',$editLoanRow);  
$smarty->assign("today",$today);
$smarty->assign("loanTypeArr",$loanTypeArr);
$smarty->assign('msg',$msg);
$smarty->display('loan.tpl');  
?>